// store.js

import React, { createContext, useReducer } from 'react'

const initialState = {
  token: localStorage.getItem('token')|| null,
  modelVisible: false,
  loginStatus: 1 , //0 注册 1登录
  user: localStorage.getItem("user")? JSON.parse(localStorage.getItem("user")) :  null,
  messageList:localStorage.getItem("messageList")? JSON.parse(localStorage.getItem("messageList")) :[],
  isReply:false, // 正在回复
  pathname:"" , // 路由
  isStop:false
}

// 创建 Context 对象
export const AppContext = createContext()

const reducer = (state, action) => {
  switch (action.type) {
    case 'SET_TOKEN':
      return { ...state, token: action.payload }
    case 'SET_VISIBLE':
      return { ...state, modelVisible: action.payload }
    case 'SET_STATUS':
        return { ...state, loginStatus: action.payload }
    case 'SET_USER':
        return { ...state, user: action.payload}
    case 'SET_MESSAGE_LIST':
        localStorage.setItem("messageList", JSON.stringify(action.payload) )
        return { ...state, messageList: action.payload}
    case 'UPDATE_LAST_MESSAGE':
        const messages = state.messageList;
        messages.splice(-1, 1, action.payload);
        localStorage.setItem("messageList", JSON.stringify(messages))
        return { ...state, messageList: messages}
    case 'SET_IS_REPLY':
      return { ...state, isReply: action.payload }
    case 'SET_PATHNAME':
        return { ...state, pathname: action.payload }
      case 'SET_IS_STOP':
      return { ...state, isStop: action.payload }
    default:
      return state
  }
}

// 创建 Context Provider 组件
export const AppProvider = ({ children }) => {
  const [state, dispatch] = useReducer(reducer, initialState)

  return (
    <AppContext.Provider value={{ state, dispatch }}>
      {children}
    </AppContext.Provider>
  )
}
